package com.gccloud.tgyfirst.service.demo.service.impl;

import com.gccloud.tgyfirst.service.demo.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * @author qianxing
 * @version 1.0
 * @date 2021/5/18 9:35
 */
@Service
@Slf4j
public class FileServiceImpl implements IFileService {



    @Override
    public String putObject(String filePath, String objectName, InputStream stream) {

        try {
            String fileName = filePath + "/" + objectName;
            BufferedInputStream in = new BufferedInputStream(stream);
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
            int len;
            byte[] bytes = new byte[1024];
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
                out.flush();
            }
            in.close();
            out.close();
            return fileName;
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return "上传失败，请重试";
    }


    @Override
    public void download(String filePath, OutputStream out) {
        try {
            File file = new File(filePath);
            InputStream is = new FileInputStream(file);
            IOUtils.copy(is, out);
            is.close();
            out.close();
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }
    }
}
